/*
 * OrderButtonLayout.java
 * business
 *
 * Created by ChenTao on 2017/3/2.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.widget.view;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import com.yidiandao.business.R;
import com.yidiandao.business.data.bean.Goods;
import com.yidiandao.business.data.bean.ValueBean;
import com.yidiandao.business.data.model.IOrderModel;
import com.yidiandao.business.data.model.OrderModel;
import com.yidiandao.business.ui.main.shoppingcart.confirmorder.ConfirmOrderActivity;
import com.yidiandao.business.ui.orderabout.aftersale.AfterSaleActivity;
import com.yidiandao.business.ui.orderabout.aftersaleprogress.AfterSaleProgressActivity;
import com.yidiandao.business.ui.orderabout.banktransferinfo.BankTransferInfoActivity;
import com.yidiandao.business.ui.orderabout.ordercertificate.OrderCertificateActivity;
import com.yidiandao.business.ui.orderabout.rate.RateActivity;
import com.yidiandao.business.ui.orderabout.unifiedrate.UnifiedRateActivity;
import com.yidiandao.business.ui.url.UrlActivity;
import com.yidiandao.business.ui.widget.dialog.BusinessDialog;
import com.yidiandao.business.ui.widget.dialog.BusinessListDialog;
import com.yidiandao.business.ui.widget.dialog.LoadingDialog;
import com.yidiandao.business.utils.UIUtils;
import com.yidiandao.business.utils.UmengUtils;

import java.util.List;

/**
 * 订单中订单按钮
 */
public class OrderButtonLayout extends ViewGroup {

    private String TAG = OrderButtonLayout.class.getSimpleName();

    private Context context;

    /**
     * 水平间隔,默认15dp
     */
    private int mHorSpacing = UIUtils.dp2px(15);

    private int mChildHeight;

    private OrderModel mOrderModel;
    private LoadingDialog mLoadingDialog;
    private Activity mActivity;
    private OnItemClickListener mListener;

    public OrderButtonLayout(Context context) {
        this(context, null);
    }

    public OrderButtonLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();

        // 开始计算左边位置 需要加上paddingLeft
        int childLeft = paddingLeft;

        View childView;
        for (int i = 0; i < getChildCount(); i++) {
            childView = getChildAt(i);
            // 测量 Child
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
            // 获取Child的宽度
            int childWidth = childView.getMeasuredWidth();
            mChildHeight = childView.getMeasuredHeight() + paddingTop + paddingBottom;

            childLeft += childWidth + mHorSpacing;
        }

        // 最后加上paddingRight
        int widthSize = childLeft;

        setMeasuredDimension(widthSize, MeasureSpec.getSize(mChildHeight));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();

        int childLeft = paddingLeft;
        int childTop = paddingTop;
        int childBottom = paddingBottom;

        View childView;
        for (int i = 0; i < getChildCount(); i++) {
            childView = getChildAt(i);

            if (childView.getVisibility() == GONE) {
                continue;
            }

            int childWidth = childView.getMeasuredWidth();
            int childHeight = childView.getMeasuredHeight();

            childView.layout(
                    childLeft,
                    childTop,
                    childLeft + childWidth,
                    childHeight + childBottom + childTop);

            childLeft = childLeft + childWidth + mHorSpacing;
        }
    }

    /**
     * 给Layout设置数据
     */
    public void setData(Activity activity, String orderId, final List<String> buttons,
                        List<Goods> goodsList) {
        mActivity = activity;
        removeAllViews();
        mOrderModel = new OrderModel();
        mLoadingDialog = new LoadingDialog(activity);
        setButtonsData(orderId, buttons, goodsList);
    }

    private void setButtonsData(String orderId, List<String> buttons, List<Goods> goodsList) {
        if (buttons != null && buttons.size() > 0) {
            for (int i = 0; i < buttons.size(); i++) {
                OrderStatusView view = new OrderStatusView(context);
                final String name = buttons.get(i);
                if(name.equals("pay_bank"))
                    continue;
                setTextAndClick(orderId, view, name, goodsList);
                addView(view);
            }
        }
    }

    private void setTextAndClick(final String orderId, final OrderStatusView view,
                                 final String name, final List<Goods> goodsList) {
        switch (name) {
            case "cancle":
                view.setText(UIUtils.getString(R.string.order_cancleorder));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UmengUtils.onEvent(mActivity, R.string.umeng_order_cancle);
                        final String sts[] = UIUtils.getStringArray(R.array.order_cancle);
                        new BusinessListDialog.Builder(mActivity)
                                .setTitle(R.string.order_cancleorder)
                                .setMessage(R.string.cancel_order_tips)
                                .setItems(
                                        sts,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog, int which) {
                                                cancelOrder(view, sts[which], orderId);
                                            }
                                        })
                                .create()
                                .show();
                    }
                });
                break;
            case "pay":
                view.setText(UIUtils.getString(R.string.order_pay));
                //付款
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UmengUtils.onEvent(mActivity, R.string.umeng_order_pay);
                        //                        ChooseBankCardActivity.actionStart(mActivity);
                        onlinePay(view, orderId);

                    }
                });
                break;
            case "pay_bank":
                view.setText(UIUtils.getString(R.string.order_pay_sure));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 银行卡转账信息
                        BankTransferInfoActivity.actionStart(mActivity, orderId);
                    }
                });
                break;
            case "upload_img":
                view.setText(UIUtils.getString(R.string.order_certificate));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 上传凭证
                        OrderCertificateActivity.actionStart(mActivity, orderId);
                    }
                });
                break;
            case "receive":
                view.setVisibility(GONE);
                view.setText(UIUtils.getString(R.string.order_receipt));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                      /*  // 扫码收货
                        UmengEventUtils.onEvent(mActivity, R.string.umeng_order_zxing_sure);
                        BindQrCodeActivity.actionStart(mActivity);*/
                    }
                });
                break;
            case "comment":
                view.setText(UIUtils.getString(R.string.order_valued));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //评价
                        valueGoodsAndOrder(goodsList, orderId);
                    }
                });
                break;
            case "again":
                view.setText(UIUtils.getString(R.string.exchange_after_sale_buy));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UmengUtils.onEvent(mActivity, R.string.umeng_order_buy_again);
                        // 订单详情再次购买
                        buyAgain(view, orderId);
                    }
                });
                break;
            case "apply":
                view.setText(UIUtils.getString(R.string.exchange_after_sale_apply));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 申请售后
                        UmengUtils.onEvent(mActivity, R.string.umeng_order_after_sale);
                        AfterSaleActivity.actionStart(mActivity, orderId);
                    }
                });
                break;
            case "server":
                view.setText(UIUtils.getString(R.string.exchange_after_sale_progress));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 售后进度
                        AfterSaleProgressActivity.actionStart(mActivity, orderId);
                    }
                });
                break;
            case "receive_all":
                view.setText(UIUtils.getString(R.string.order_receive));
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //确认收货
                        UmengUtils.onEvent(mActivity, R.string.umeng_order_press_sure);
                        new BusinessDialog.Builder(mActivity)
                                .setTitle(R.string.dialog_receive_tip)
                                .setPositiveButton(
                                        R.string.dialog_sure,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog, int which) {
                                                receiveSure(view, orderId);
                                            }
                                        })
                                .setNegativeButton(R.string.dialog_cancel, null)
                                .create()
                                .show();
                    }
                });
                break;
        }
    }

    /**
     * 在线支付 立即付款
     */
    private void onlinePay(final OrderStatusView view, String orderId) {
        mLoadingDialog.show();
        view.setEnabled(false);
        mOrderModel.onlinePay(TAG, orderId, new IOrderModel.OnLinePayListener() {
            @Override
            public void onSuccess(String url) {
                UrlActivity.actionStart(mActivity, url);
            }

            @Override
            public void onFinal() {
                mLoadingDialog.dismiss();
                view.setEnabled(true);
            }
        });
    }

    /**
     * 确认收货
     */
    private void receiveSure(final OrderStatusView view, String orderId) {
        mLoadingDialog.show();
        view.setEnabled(false);
        mOrderModel.confirmReceive(
                TAG,
                orderId,
                new IOrderModel.onAccessNetListener() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast(UIUtils.getString(R.string.order_receipt_success));
                        if (null != mListener) {
                            mListener.onItemClick();
                        }
                    }

                    @Override
                    public void onFinal() {
                        mLoadingDialog.dismiss();
                        view.setEnabled(true);
                    }
                });
    }

    /**
     * 评价订单
     */
    private void valueGoodsAndOrder(List<Goods> goodsList, String orderId) {
        UmengUtils.onEvent(mActivity, R.string.umeng_order_value);
        if (goodsList.size() > 1) {
            UnifiedRateActivity.actionStart(mActivity, orderId);
        } else {
            ValueBean bean = new ValueBean();
            bean.setShowRatingBar(true);
            bean.setOrder_id(orderId);
            bean.setGoods_id(goodsList.get(0).getGoodsId());
            bean.setRec_id(goodsList.get(0).getRecId());
            bean.setGoods_thumb(goodsList.get(0).getGoodsThumb());
            RateActivity.actionStart(mActivity, bean);
        }
    }

    /**
     * 再次购买
     */
    private void buyAgain(final OrderStatusView view, String orderId) {
        mLoadingDialog.show();
        view.setEnabled(false);
        mOrderModel.buyAgain(orderId, TAG, new IOrderModel.OnBuyAgainListener() {
            @Override
            public void onSuccess(String recJson) {
                ConfirmOrderActivity.actionStart(mActivity, false);
            }

            @Override
            public void onFailed() {
                // 再次购买的库存判断由后台判定
            }

            @Override
            public void onFinal() {
                mLoadingDialog.dismiss();
                view.setEnabled(true);
            }
        });
    }


    /**
     * 取消订单
     */
    private void cancelOrder(final OrderStatusView view, String reason, String orderId) {
        mLoadingDialog.show();
        view.setEnabled(false);
        mOrderModel.cancelOrder(
                TAG,
                orderId,
                reason,
                new IOrderModel.onAccessNetListener() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast(UIUtils.getString(R.string.order_cancleOrder_success));
                        if (null != mListener) {
                            mListener.onItemClick();
                        }
                    }

                    @Override
                    public void onFinal() {
                        mLoadingDialog.dismiss();
                        view.setEnabled(true);
                    }
                });
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick();
    }
}
